import sys
import requests
import json
from PyQt5.QtWidgets import QLabel, QPushButton, QWidget, QApplication, \
    QDesktopWidget, QMessageBox, QTableView, QHeaderView, QRadioButton, QLineEdit
from PyQt5.QtGui import QIcon, QStandardItemModel, QStandardItem
from PyQt5.QtCore import pyqtSignal
import constance

url = "http://lenjon.top:9090/"


# 函数功能：根据i（列）的值返回dic中对应的string
def judge(i):
    if i == 0:
        return 'bookId'
    if i == 1:
        return 'borrowerId'
    if i == 2:
        return 'borrowTime'
    if i == 3:
        return 'returnTime'
    if i == 4:
        return 'renewTimes'


# 函数功能：给model(QStandardItemModel类型)赋值 data(dic类型)为值域 page为所需页码(每页最多可储存15条记录)
def fill(model, data):
    index = data['size']
    print(index)
    for r in range(15):
        for c in range(5):
            if r < index:
                item = QStandardItem('%s' % data['list'][r][judge(c)])
                model.setItem(r, c, item)
            else:
                item = QStandardItem('')
                model.setItem(r, c, item)


# 一般借阅记录
def content_all(page):
    headers = {
        'Content_Type': "application/json;charset=uft8",
        'Accept': '*/*',
        'token': constance.get_token()
    }
    res = requests.get(url + '/manager/allLog?pageNum=' + page, headers=headers)
    res_data = json.loads(res.text)
    constance.set_content_all(res_data['data'])


# 已归还借阅记录
def content_t(page):
    headers = {
        'Content_Type': "application/json;charset=uft8",
        'Accept': '*/*',
        'token': constance.get_token()
    }
    res = requests.get(url + '/manager/hasReturnLog?pageNum=' + page, headers=headers)
    res_data = json.loads(res.text)
    constance.set_content_t(res_data['data'])


# 未归还借阅记录
def content_f(page):
    headers = {
        'Content_Type': "application/json;charset=uft8",
        'Accept': '*/*',
        'token': constance.get_token()
    }
    res = requests.get(url + '/manager/noReturnLog?pageNum=' + page, headers=headers)
    res_data = json.loads(res.text)
    constance.set_content_f(res_data['data'])


class history(QWidget):
    s1 = pyqtSignal()

    def rt(self):
        self.s1.emit()

    def __init__(self):
        super().__init__()
        self.condition = 1
        self.p = 1

    def initUI(self):
        self.r1 = QRadioButton('所有图书', self)
        self.r2 = QRadioButton('已归还', self)
        self.r3 = QRadioButton('未归还', self)

        self.r1.move(150, 15)
        self.r2.move(450, 15)
        self.r3.move(750, 15)

        self.r1.setChecked(False)
        self.r2.setChecked(False)
        self.r3.setChecked(False)

        self.r1.toggled.connect(lambda: self.bt(self.r1))
        self.r2.toggled.connect(lambda: self.bt(self.r2))
        self.r3.toggled.connect(lambda: self.bt(self.r3))

        self.model = QStandardItemModel(15, 5)
        self.model.setHorizontalHeaderLabels(['图书ID', '用户ID', '借阅日期', '归还日期', '续借次数'])
        content_all('1')
        self.k = constance.get_content_all()
        fill(self.model, self.k)

        self.table = QTableView(self)
        self.table.setModel(self.model)
        self.table.horizontalHeader().setStretchLastSection(True)
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.table.move(0, 40)
        self.table.setFixedSize(1000, 477)

        self.bt1 = QPushButton('上一页', self)
        self.bt2 = QPushButton('下一页', self)
        self.bt3 = QPushButton('确定', self)
        self.l1 = QLabel('跳转至第', self)
        self.l2 = QLabel('页', self)
        self.e1 = QLineEdit(self)

        self.l1.setGeometry(420, 525, 100, 25)
        self.l2.setGeometry(495, 525, 40, 25)
        self.e1.setGeometry(470, 530, 20, 16)
        self.bt1.setGeometry(720, 525, 100, 25)
        self.bt2.setGeometry(850, 525, 100, 25)
        self.bt3.setGeometry(515, 528, 50, 20)

        self.bt1.clicked.connect(self.lastPage)
        self.bt2.clicked.connect(self.nextPage)
        self.bt3.clicked.connect(self.flip)

        self.b1 = QPushButton('返回', self)
        self.b2 = QPushButton('退出', self)
        self.b1.clicked.connect(self.rt)
        self.b2.clicked.connect(QApplication.instance().quit)
        self.b1.setGeometry(50, 525, 100, 25)
        self.b2.setGeometry(180, 525, 100, 25)

        self.resize(1000, 560)
        self.setWindowTitle('历史借阅')
        self.setWindowIcon(QIcon('icon.png'))
        self.show()

    def center(self):
        x = self.frameGeometry()
        y = QDesktopWidget().availableGeometry().center()
        x.moveCenter(y)
        self.move(x.topLeft())

    # def closeEvent(self, event):
    #     qt = QMessageBox(QMessageBox.Question, "系统提示", "是否退出")
    #     yap = qt.addButton("是", QMessageBox.YesRole)
    #     qt.addButton("否", QMessageBox.NoRole)
    #     qt.setWindowIcon(QIcon('Icon.png'))
    #     qt.exec_()
    #     if qt.clickedButton() == yap:
    #         event.accept()
    #     else:
    #         event.ignore()

    def bt(self, btn):
        if btn.text() == '所有图书':
            if btn.isChecked():
                self.condition = 1
                content_all('1')
                self.k = constance.get_content_all()
        if btn.text() == '已归还':
            if btn.isChecked():
                self.condition = 2
                content_t('1')
                self.k = constance.get_content_t()
        if btn.text() == '未归还':
            if btn.isChecked():
                self.condition = 3
                content_f('1')
                self.k = constance.get_content_f()
        fill(self.model, self.k)
        self.e1.setText('1')

    def flip(self):
        index = self.e1.text()
        if self.condition == 1:
            content_all(index)
            self.k = constance.get_content_all()
        if self.condition == 2:
            content_t(index)
            self.k = constance.get_content_t()
        if self.condition == 3:
            content_f(index)
            self.k = constance.get_content_f()

        q = self.k['list']
        print(q)
        if q:
            self.p = int(index)
            fill(self.model, self.k)
        else:
            msg = QMessageBox(QMessageBox.Warning, '系统提示', '目标为空')
            msg.addButton('返回', QMessageBox.NoRole)
            msg.setWindowIcon(QIcon('Icon.png'))
            msg.exec_()

    def lastPage(self):
        if self.p == 1:
            msg = QMessageBox(QMessageBox.Warning, '系统提示', '当前已在第一页')
            msg.addButton('返回', QMessageBox.NoRole)
            msg.setWindowIcon(QIcon('Icon.png'))
            msg.exec_()
        else:
            self.p -= 1
            s = str(self.p)
            if self.condition == 1:
                content_all(s)
                self.k = constance.get_content_all()
            if self.condition == 2:
                content_t(s)
                self.k = constance.get_content_t()
            if self.condition == 3:
                content_f(s)
                self.k = constance.get_content_f()
            fill(self.model, self.k)

    def nextPage(self):
        if self.k['isLastPage']:
            msg = QMessageBox(QMessageBox.Warning, '系统提示', '当前已是最后一页')
            msg.addButton('返回', QMessageBox.NoRole)
            msg.setWindowIcon(QIcon('Icon.png'))
            msg.exec_()
        else:
            self.p += 1
            s = str(self.p)
            if self.condition == 1:
                content_all(s)
                self.k = constance.get_content_all()
            if self.condition == 2:
                content_t(s)
                self.k = constance.get_content_t()
            if self.condition == 3:
                content_f(s)
                self.k = constance.get_content_f()
            fill(self.model, self.k)


if __name__ == '__main__':
    constance.init()
    app = QApplication(sys.argv)
    a = history()
    a.initUI()
    sys.exit(app.exec_())
